/**
 * Created by zhanglihe on 15/9/9.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'collection',
    'model',
    'dialog'
], function ($, common, ready, template, Collection, Model, dialog) {

    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            var _this = this;
            //地区
            $.ajax({
                url: _global.url.api + 'regions',
                type: 'get',
                async: false,
                data: {depth: 2},
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('region', res.data);
                    }
                }
            });
            loading();
            this.event();
            this.fetch();
        },

        fetch: function (_args) {
            var args = _args || {};
            args.limit = 10;
            args.offset = 0;
            var that = this;
            that.collection = new Collection({
                container: 'data-list',
                template: 'data-item',
                url: _global.url.api + 'agencys',
                condition: args,
                model: {
                    tag_name: 'tr',
                    url: {
                        put: _global.url.api + 'agency/{id}'
                    },
                    event: {
                        '.item-edit:click': 'edit',
                        '.item-enable:click': 'enable',
                        '.item-disable:click': 'disable',
                        '.glyphicon-repeat:click': 'repeat'
                    },
                    enable: function (e) {
                        e.preventDefault();
                        this.data.status = 1;
                        this.put();
                    },
                    disable: function (e) {
                        e.preventDefault();
                        this.data.status = 2;
                        this.put();
                    },
                    edit: function (e) {
                        e.preventDefault();
                        var _this = this;

                        dialog({
                            title: '编辑城市运营：' + _this.data.name,
                            width: 800,
                            content: template('edit-tpl', {data: _this.data, region: that.region}),
                            ok: function () {
                                _this.data.can_login_site = $('input[name="can_login_site"]').is(':checked') ? 1 : 0;
                                if (!_this.put()) {
                                    console.log('put false');
                                    return false;
                                } else {
                                    that.collection.reload();
                                }
                            },
                        }).show();
                        //地区联动
                        $('.province').on('change', function () {
                            $('select[name="city"]').find('option').eq(0).nextAll().remove();
                            var id = $(this).val();
                            var city = that.region[id].child;
                            for (var n in city) {
                                $('select[name="city"]').append('<option value="' + city[n].id + '">' + city[n].name + '</option>')
                            }
                        });

                        //绑定表单元素更改事件
                        $('input, select, textarea').on('change', function (e) {
                            _this.change(e);
                        });

                    },
                    repeat: function (e) {
                        e.preventDefault();
                        var _this = this;
                        var model = new Model({url: _global.url.api + 'agencier_password/' + _this.data.id});
                        model.data = {id: _this.data.id, email: _this.data.email};

                        dialog({
                            content: '确定要继续重置密码为123456吗？',
                            ok: function () {
                                if (model.put()) {
                                    that.collection.reload();
                                } else {
                                    alert('重置失败');
                                }
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    change: function (e) {
                        this.data[$(e.target).attr('name')] = $(e.target).val();
                    }
                },
                callback: function () {
                    loaded();
                }
            });
            this.collection.fetch();
        },
        set: function ($k, $v) {
            this[$k] = $v;
        },
        event: function () {
            var _this = this;
            $('#btn-add').on('click', function (e) {
                _this.data = {}; ////表单临时变量
                e.preventDefault();
                dialog({
                    title: '添加城市运营',
                    width: 800,
                    content: template('edit-tpl', {data: _this.data, region: _this.region}),
                    ok: function () {
                        can_login_site = $('input[name="can_login_site"]').is(':checked') ? 1 : 0;
                        data = {
                            name: $('#name').val(),
                            contact: $('#contact').val(),
                            tel: $('#tel').val(),
                            mobile: $('#mobile').val(),
                            about_url: $('#about_url').val(),
                            flow_commission: $('[name="flow_commission"]').val(),
                            pool_commission: $('[name="pool_commission"]').val(),
                            province: $('#province').val(),
                            city: $('#city').val(),
                            email: $('#email').val(),
                            password: $.trim($('#password').val()),
                            can_login_site: can_login_site
                        };
                        if (!new Model({
                                url: _global.url.api + 'agency',
                                data: data,
                                valid_config: {
                                    name: 'required',
                                    email: 'email',
                                    password: 'required'
                                }
                            }).post()) {
                            return false;
                        }
                        _this.fetch();
                    }, cancel: function () {
                    }
                }).show();
                //地区联动
                $('.province').on('change', function () {
                    $('select[name="city"]').find('option').eq(0).nextAll().remove();
                    var id = $(this).val();
                    var city = _this.region[id].child;
                    for (var n in city) {
                        $('select[name="city"]').append('<option value="' + city[n].id + '">' + city[n].name + '</option>')
                    }
                });
                //绑定表单元素更改事件
                $('input, select, textarea').on('change', function (e) {
                    _this.change(e);
                });
            });

            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.reload();
            });

            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = '';
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.condition.type = $("#type").val();
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });
        },

        change: function (e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        }
    };

    new index();

});